import { createStore, MutationPayload, Store } from 'vuex';
import router from '@/router';
import { IUser } from '@/api/users';
import { IMenu } from '@/api/menus';

/**
 * vuex持久化
 * @param store store对象
 */
const vuexPersist = (store: Store<any>) => {
  const key = 'vuexPersist';
  const storage = window.sessionStorage;

  const data = storage.getItem(key);
  data && store.replaceState(JSON.parse(data));

  /**
   * 注册mutations的回调函数
   */
  store.subscribe((mutation: MutationPayload, state: any) => {
    storage.setItem(key, JSON.stringify(state));
  });
}

export default createStore({
  state: {
    user: <IUser>{},
    myMenus: <IMenu[]>[]
  },
  getters: {
    /**
     * token
     */
    token(state) {
      return state.user.password;
    }
  },
  mutations: {
    /**
     * 设置用户信息
     */
    setUser(state, payload) {
      state.user = payload;
    },
    /**
     * 设置token
     * @param state 
     * @param payload 
     */
    setToken(state, payload) {
      state.user.password = payload;
    },
    /**
     * 设置我的菜单
     * @param state 
     * @param payload 
     */
    setMyMenus(state, payload) {
      state.myMenus = payload;
    }
  },
  actions: {
    /**
     * 退出登录
     */
    exit({ commit }) {
      commit('setUser', {});
      router.replace({ name: 'login' });
    }
  },
  plugins: [vuexPersist],
  modules: {
  }
})
